/**
 *
 */
package com.yangtao.prototype.listener;

import com.yangtao.framework.service.ServiceLocator;
import com.yangtao.prototype.system.dao.MenuTreeDao;
import com.yangtao.prototype.system.domain.MenuTree;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 杨涛
 */
public class ResourceLoaderListenner implements ServletContextListener {
	Integer count = 0;

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	@Override
	public void contextInitialized(ServletContextEvent event) {
//		//TODO 初始化组织机构数据
//		OrganizationDao organizationDao = ServiceLocator.getInstance()
//				.getService(OrganizationDao.class);
//		organizationDao.batchExecute("delete from Organization");
//		Organization organization = new Organization();
//		organization.setOrgCode("root");
//		organization.setName("XXXX股份有限公司");
//		organization.setLevel(0);
//		organization.setPath("root");
//		organization.setState(Byte.valueOf("1"));
//		organizationDao.save(organization);
//		//TODO 初始化用户数据
//		UserDao userDao = ServiceLocator.getInstance()
//				.getService(UserDao.class);
//		SysUser sysUser = new SysUser();
//		sysUser.setUserCode("admin");
//		sysUser.setUserName("admin");
//		sysUser.setPassword("admin");
//		sysUser.setActive(Byte.valueOf("1"));
//		sysUser.setExpireDate(new Date("2020-12-30"));
//		sysUser.setEmail("walle1027@gmail.com");
//		sysUser.setOrganization(organization);
//		sysUser.setPhone("15900413002");
//		userDao.save(sysUser);
		//TODO 初始化菜单数据
		InputStream stream = null;
		MenuTree first = null;
		try {
			MenuTreeDao menuTreeDao = ServiceLocator.getInstance()
					.getService(MenuTreeDao.class);
			Integer maxlevel = menuTreeDao
					.findUnique("select max(level) from MenuTree");
			maxlevel = maxlevel == null ? 0 : maxlevel;
			for (int i = maxlevel; i > 0; i--) {
				//菜单和功能权限做了关联了，如果要删除菜单，要先删除功能权限
				menuTreeDao.batchExecute("delete from FunctionAuthority fa where" +
						" exists (select 1 from MenuTree m where m=fa.menu and m.level=?)", i);
				//删除菜单
				menuTreeDao.batchExecute("delete from MenuTree where level=?", i);
			}
			SAXReader reader = new SAXReader();
			stream = getClass().getClassLoader()
					.getResourceAsStream("menu.xml");
			Document document = reader.read(stream);
			Element root = document.getRootElement();
			Iterator modules = root.elementIterator("Module");

			while (modules.hasNext()) {
				count++;
				Element element = (Element) modules.next();
				first = new MenuTree();
				first.setId(element.attributeValue("id"));
				first.setName(element.attributeValue("name"));
				first.setLevel(Integer
						.parseInt(element.attributeValue("level")));
				first.setIcon(element.attributeValue("icon"));
				first.setUrl(element.attributeValue("url"));
				first.setDispOrder(count);
				addMoudles(element, first);
				menuTreeDao.save(first);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 递归加载子级菜单
	 *
	 * @param element
	 * @param mt
	 */
	@SuppressWarnings("unchecked")
	private void addMoudles(Element element, MenuTree mt) {
		List<MenuTree> subMenus = new ArrayList<MenuTree>();
		for (Iterator it = element.elementIterator(); it.hasNext(); ) {
			count++;
			Element item = (Element) it.next();
			MenuTree subMenu = new MenuTree();
			subMenu.setId(item.attributeValue("id"));
			subMenu.setName(item.attributeValue("name"));
			subMenu.setLevel(Integer.parseInt(item.attributeValue("level")));
			subMenu.setIcon(item.attributeValue("icon"));
			subMenu.setUrl(item.attributeValue("url"));
			subMenu.setParentMenu(mt);
			subMenu.setDispOrder(count);
			addMoudles(item, subMenu);
			subMenus.add(subMenu);
		}
		mt.setSubMenus(subMenus);
	}
}
